﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Configuration;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel.Common
{
    public class ExitAppliacationViewModel : ViewModelBase
    {
        //从App.config中获取退出程序的密码
        private string ExitPassword = ConfigurationManager.ConnectionStrings["ExitPassword"].ConnectionString;
        /// <summary>
        /// 退出系统命令
        /// </summary>
        public DelegateCommand ExitApplicationCommand { get; set; }
        /// <summary>
        /// 关闭当前窗体命令
        /// </summary>
        public DelegateCommand HideExitApplicationWindowCommand { get; set; }

        /// <summary>
        /// 退出系统密码
        /// </summary>
        private string _ExtiPassword;
        /// <summary>
        /// 退出系统密码
        /// </summary>
        public string ExtiPassword
        {
            set
            {
                _ExtiPassword = value;
                RaisePropertyChanged("ExtiPassword");
            }
            get
            {
                return _ExtiPassword;
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        public ExitAppliacationViewModel()
        {
            //使用委托初始化退出系统命令
            ExitApplicationCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ExitAppHandler)
            };
            //使用委托初始化关闭当前窗体命令命令
            HideExitApplicationWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideExitApplicationWindowHandler)
            };
        }
        /// <summary>
        /// 退出程序验证处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void ExitAppHandler(object obj)
        {
            if (_ExtiPassword != null && _ExtiPassword.Trim().Length > 0)
            {
                if (XyhUtils.IsHasSQLInject(_ExtiPassword))
                {
                    WindowManager.ShowWarning("警告", "退出密码不可使用包含SQL注入关键词进行退出操作！");
                    return;
                }
                if (_ExtiPassword == ExitPassword)
                {
                    Environment.Exit(0);
                }
                else
                {
                    WindowManager.ShowWarning("警告", "退出密码不正确。");
                }
            }
            else
            {
                WindowManager.ShowWarning("警告", "请输入退出密码。");
            }

        }
        /// <summary>
        /// 关闭当前窗体处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void HideExitApplicationWindowHandler(object obj)
        {
            ExtiPassword = null;
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "CloseWindowsBoundToMe"));
        }
    }
}
